/*
 * Reksio - Memory Map Editor
 * Copyright (C) 2023 CERN
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * In applying this licence, CERN does not waive the privileges and immunities
 * granted to it by virtue of its status as an Intergovernmental Organization or
 * submit itself to any jurisdiction.
 */

#include "mainwindow.h"
#include <QApplication>
#include <QTimer>
#include <QCommandLineParser>
#include "customexceptionhandler.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    // app info - used by QSettings
    QCoreApplication::setOrganizationName("CERN");
    QCoreApplication::setOrganizationDomain("cern.ch");
    QCoreApplication::setApplicationName("reksio");
    QCoreApplication::setApplicationVersion(REKSIO_VERSION);
    CustomExceptionHandler exc_handler(QCoreApplication::applicationDirPath());

    QCommandLineParser parser;

	QString desc = "Reksio " + QString(REKSIO_VERSION) +
				" - Cheby/YAML memory map editor.\n\n"
				"Python dependiencies (based on git tag): \n"
				" - PyCheby " + QString(PYCHEBY_VERSION) + "\n"
				" - cheby " + QString(CHEBY_VERSION) + "\n"
				" - cheburashka " + QString(CODE_GEN_VERSION);

    parser.setApplicationDescription(desc);
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("file", "Memory map file to open");

    QCommandLineOption validateOnlyOption("try-to-load-only", "Do not start the graphical mode, only validate memory map and return 0 or 1");
    parser.addOption(validateOnlyOption);

    parser.process(a);

    const bool validateOnly = parser.isSet(validateOnlyOption);

    const QStringList args = parser.positionalArguments();

    if(validateOnly)
    {
        if(args.size() == 1)
        {
            MainWindow w(false); // do not redirect stderr/out/qDebug/../ to the graphical console
            const bool result = w.openFile(args.first(), true);
            return !result;
        }
        else
        {
            qWarning() << "If --try-to-load-only is set, a path to memory map file must be provided";
            return 1;
        }
    }
    else
    {
        MainWindow w;
        if(args.size() == 1)
        {
            w.openFile(args.first(), false);
        }
        w.show();
        return a.exec();
    }
}
